#
# Builds the PyMite VM as an archive
#

# Configure the contents of pmstdlib by editing this list
PMSTDLIB_SOURCES = ../lib/__bi.py \
                   ../lib/sys.py

TARGET ?= DESKTOP
HEAP_SIZE ?= 0x1000

PMIMGCREATOR := ../tools/pmImgCreator.py
DEFS = -DTARGET_$(TARGET) -DHEAP_SIZE=$(HEAP_SIZE)
CFLAGS = -Os -Wall -Wstrict-prototypes -Werror $(DEFS)
ARFLAGS := rcs
SOURCE_IMG := pmstdlib_img.c
SOURCE_NAT := pmstdlib_nat.c
SOURCES = $(wildcard *.c) $(SOURCE_IMG) $(SOURCE_NAT)
OBJECTS = $(SOURCES:.c=.o)
PRODUCT_VM := libpmvm.a
INDENT := $(call pathsearch,indent)

#
# If GDB debugging is wanted
#
ifeq ($(DEBUG),true)
	DEFS += -g -ggdb -D__DEBUG__=1
endif

#
# Target-specific definitions
#
ifeq ($(TARGET), DESKTOP)
	CFLAGS += -ansi
	SOURCES += plat/desktop.c
else
ifeq ($(TARGET), AVR)
	TARGET_MCU ?= atmega103
	F_CPU ?= 4000000UL
	UART_BAUD ?= 19200UL
	AR = avr-ar
	CC = avr-gcc
	SIZE = avr-size
	CFLAGS += -mmcu=$(TARGET_MCU) 
	DEFS += -DTARGET_MCU=$(TARGET_MCU) -DF_CPU=$(F_CPU) -DUART_BAUD=$(UART_BAUD)
	SOURCES += plat/avr.c
	PMSTDLIB_SOURCES += ../lib/avr.py
else
ifeq ($(TARGET), AT91SAM7)
	TARGET_MCU ?= arm7tdmi
	AR = arm-elf-ar
	CC = arm-elf-gcc
	SIZE = arm-elf-size
	CFLAGS += -mcpu=$(TARGET_MCU) -mthumb -mthumb-interwork -DTARGET_MCU=$(TARGET_MCU)
	SOURCES += plat/at91sam7.c
endif
endif
endif

#
# If Interactive PyMite (ipm) is wanted
#
ifeq ($(IPM),true)
	PMSTDLIB_SOURCES += ../lib/ipm.py
endif


.PHONY: all size indent clean

# Default action is to build the archive from object files
all : $(SOURCE_IMG) $(SOURCE_NAT) $(PRODUCT_VM)

# The archive is generated by placing object files inside it
$(PRODUCT_VM) : $(PRODUCT_VM)($(OBJECTS))

# Build the standard library into an image file and native function file
$(SOURCE_IMG) $(SOURCE_NAT) : $(PMSTDLIB_SOURCES)
	$(PMIMGCREATOR) -c --memspace=flash -o $(SOURCE_IMG) --native-file=$(SOURCE_NAT) $(PMSTDLIB_SOURCES)

# Lists the size of the obejcts in the archive
size : $(PRODUCT_VM)
	@$(SIZE) $(PRODUCT_VM)

# Runs GNU indent on the source files
indent :
	$(if $(INDENT), $(INDENT) *.c *.h)

# Remove files made by default make
clean :
	@$(RM) $(PRODUCT_VM)
	@$(RM) $(OBJECTS)
	@$(RM) $(SOURCE_IMG) $(SOURCE_NAT)
